

const asar = require('asar');
const path = require('path');
const fs = require('fs-extra');
const { uuid } = require('./uuidUtil')
const { getPluginPath, mkdir, rmdir, rmFile, getUserCachePath } = require('./fileUtil')


exports.createPackage = function (pluginConfigPath) {
    const src = path.dirname(pluginConfigPath)
    let dst = path.join(src, "plugin.asar")
    process.noAsar = true
    rmFile(dst)
    return asar.createPackage(src, dst).then(() => {
        return dst
    });
}



exports.createPackageByPkg = function (pkg) {
    const thPath = fs.mkdtempSync(path.join(getUserCachePath(), "plugin"))
    const pkgPath = path.join(thPath, "plugin.json")
    fs.writeFileSync(pkgPath, JSON.stringify(pkg))
    return exports.createPackage(pkgPath)
}



exports.movePackage = function (asarPath, uuid, callback) {
    mkdir(getPluginPath())
    process.noAsar = true
    const dst = path.join(getPluginPath(), uuid + '.asar')
    rmFile(dst)
    rmdir(dst)
    process.noAsar = true
    fs.copyFile(asarPath, dst).then(() => callback())
}


exports.extractPackage = function (pluginId) {
    process.noAsar = false
    const theAsar = path.join(getPluginPath(), pluginId + '.asar')
    const thePath = path.join(getPluginPath(), pluginId)
    asar.extractAll(theAsar, thePath)
}


exports.removePackage = function (pluginId) {
    process.noAsar = true
    const thePath = path.join(getPluginPath(), pluginId)
    const theAsar = path.join(getPluginPath(), pluginId + '.asar')
    rmdir(thePath)
    rmFile(theAsar)

}